﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ExcellentCRM.DataService.Models;
using ExcellentCRM.Site.Models;
using ExcellentCRM.Site.Utilities;
using Webdiyer.WebControls.Mvc;

namespace ExcellentCRM.Site.Controllers
{
    public class DepartmentController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(SearchDeptModel sdModel)
        {
            if (ModelState.IsValid)
            {
                int pageSize = PresetValues.PageSize;
                int totalCount;
                var depts = ServiceFactory.DeptService.Search(sdModel.DeptName, pageSize,
                                                              sdModel.PageIndex,
                                                              out totalCount);
                sdModel.SearchResult =
                    new PagedList<Department>(depts, sdModel.PageIndex, pageSize, totalCount);
            }
            return View(sdModel);
        }

        public ActionResult CreateOrUpdate(long? deptId)
        {
            var dept = new Department();
            if (deptId.HasValue)
            {
                dept = ServiceFactory.DeptService.GetModel(deptId.Value);
            }
            return View(dept);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrUpdate(Department dept)
        {
            if (ModelState.IsValid)
            {
                var sr = ServiceFactory.DeptService.Save(dept);
                return Json(new AjaxResult(sr.Success, sr.Message));
            }
            return Json(new AjaxResult(false, ModelErrorStr));
        }

        [HttpPost]
        public ActionResult Delete(long deptId)
        {
            var sr = ServiceFactory.DeptService.Delete(deptId);
            return Json(new AjaxResult(sr.Success, sr.Message));
        }
    }
}
